using System;
using System.Collections.Generic;
using CodeStory.Core.ObjectEntity;

namespace CodeStory.Core.Authentication
{
	/// <summary>
	/// 
	/// </summary>
	public static class CodeStoryAuthenticationManager
	{
		/// <summary>
		/// 
		/// </summary>
		/// <param name="resourceid"></param>
		/// <param name="resourceType"></param>
		/// <param name="action"></param>
		/// <param name="roles"></param>
		/// <returns></returns>
		public static bool ValidatePermission(string resourceid, string resourceType, int action, List<Guid> roles) {
			ResourceObject ro = ResourceObject.ReadUsingUniqueField("InnerResourceID", resourceid);
			if (ro != null) {
				long p = 0;
				foreach (RoleResourceObject r in ro.RoleResource) {
					if (roles.Contains(r.RoleID)) {
						p |= r.Permission;
					}
				}
				long a = 1 << action;
				return ((p & a) == a);
			}
			return false;
		}

		public static bool ValidateUser(string userName, string password) {
			UserObject user = UserObject.ReadFirst("UserName=@UserName", "@UserName", userName);
			if (user == null) {
				return false;
			}
			if (!user.Password.Equals(password)) {
				return false;
			}
			UserContext.Current.UserName = userName;
			UserContext.Current.UserID = user.UserID;
			UserContext.Current.Roles.Clear();
			foreach (RoleObject r in user.Roles) {
				UserContext.Current.Roles.Add(r.RoleID);
			}
			return true;
		}

		public static void LoginOff() {
			UserContext.Current.LoginOff();
		}
	}
}